<template>
  <view class="games-container">
    <!-- 游戏分类 -->
    <view class="games-grid">
      <!-- 放松小游戏 -->
      <view class="game-card card" @click="openGame('bubble')">
        <view class="game-icon">🫧</view>
        <view class="game-content">
          <text class="game-name">泡泡消消乐</text>
          <text class="game-desc">点击泡泡放松心情</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>

      <!-- 呼吸游戏 -->
      <view class="game-card card" @click="openGame('flower')">
        <view class="game-icon">🌸</view>
        <view class="game-content">
          <text class="game-name">花朵呼吸</text>
          <text class="game-desc">跟随花朵节奏呼吸</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>

      <!-- 专注力训练 -->
      <view class="game-card card" @click="openGame('focus')">
        <view class="game-icon">🎯</view>
        <view class="game-content">
          <text class="game-name">专注训练</text>
          <text class="game-desc">提高注意力集中度</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>

      <!-- 手指练习 -->
      <view class="game-card card" @click="openGame('finger')">
        <view class="game-icon">👆</view>
        <view class="game-content">
          <text class="game-name">手指训练</text>
          <text class="game-desc">替代手部习惯动作</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>

      <!-- 数字游戏 -->
      <view class="game-card card" @click="openGame('number')">
        <view class="game-icon">🔢</view>
        <view class="game-content">
          <text class="game-name">数字挑战</text>
          <text class="game-desc">简单的数学游戏</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>

      <!-- 励志语录 -->
      <view class="game-card card" @click="openGame('quote')">
        <view class="game-icon">💬</view>
        <view class="game-content">
          <text class="game-name">励志语录</text>
          <text class="game-desc">每日正能量语录</text>
        </view>
        <view class="game-arrow">▶</view>
      </view>
    </view>

    <!-- 游戏模态框 -->
    <view class="modal" v-if="showGame" @click="closeGame">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ gameTitle }}</text>
          <view class="close-btn" @click="closeGame">✕</view>
        </view>
        <view class="modal-body">
          
          <!-- 泡泡消消乐 -->
          <view v-if="currentGame === 'bubble'" class="bubble-game">
            <view class="game-area">
              <view class="bubble" 
                    v-for="(bubble, index) in bubbles" 
                    :key="bubble.id"
                    :style="{ left: bubble.x + 'rpx', top: bubble.y + 'rpx', backgroundColor: bubble.color }"
                    @click.stop.self="popBubble(index)">
              </view>
            </view>
            <view class="game-stats">
              <text class="score">得分: {{ bubbleScore }}</text>
              <button class="btn btn-primary" @click="startBubbleGame">{{ bubbleGameActive ? '重新开始' : '开始游戏' }}</button>
            </view>
          </view>

          <!-- 花朵呼吸 -->
          <view v-if="currentGame === 'flower'" class="flower-game">
            <view class="flower-container">
              <view class="flower" :class="{ blooming: flowerBlooming }">🌸</view>
              <text class="flower-text">{{ flowerText }}</text>
            </view>
            <view class="flower-controls">
              <button class="btn btn-primary" @click="startFlowerBreathing">{{ flowerActive ? '停止' : '开始呼吸' }}</button>
            </view>
          </view>

          <!-- 专注训练 -->
          <view v-if="currentGame === 'focus'" class="focus-game">
            <view class="focus-area">
              <view class="focus-target" 
                    :style="{ left: targetX + 'rpx', top: targetY + 'rpx' }"
                    @click="hitTarget">
                🎯
              </view>
            </view>
            <view class="focus-stats">
              <text class="hits">命中: {{ focusHits }}</text>
              <text class="time">时间: {{ focusTime }}s</text>
              <button class="btn btn-primary" @click="startFocusGame">{{ focusActive ? '重新开始' : '开始游戏' }}</button>
            </view>
          </view>

          <!-- 手指训练 -->
          <view v-if="currentGame === 'finger'" class="finger-game">
            <view class="finger-area">
              <view class="finger-sequence">
                <view class="finger-btn" 
                      v-for="(finger, index) in fingerSequence" 
                      :key="index"
                      :class="{ active: currentFingerIndex === index, pressed: finger.pressed }"
                      @click="pressFinger(index)">
                  {{ finger.emoji }}
                </view>
              </view>
            </view>
            <view class="finger-stats">
              <text class="progress">进度: {{ fingerProgress }}/{{ fingerSequence.length }}</text>
              <button class="btn btn-primary" @click="startFingerGame">重新开始</button>
            </view>
          </view>

          <!-- 数字游戏 -->
          <view v-if="currentGame === 'number'" class="number-game">
            <view class="number-question">
              <text class="question">{{ numberQuestion }}</text>
            </view>
            <view class="number-input">
              <input type="number" v-model="numberAnswer" placeholder="输入答案" />
              <button class="btn btn-primary" @click="checkAnswer">确认</button>
            </view>
            <view class="number-stats">
              <text class="correct">正确: {{ numberCorrect }}</text>
              <text class="wrong">错误: {{ numberWrong }}</text>
            </view>
          </view>

          <!-- 励志语录 -->
          <view v-if="currentGame === 'quote'" class="quote-game">
            <view class="quote-container">
              <text class="quote-text">{{ currentQuote.text }}</text>
              <text class="quote-author">—— {{ currentQuote.author }}</text>
            </view>
            <view class="quote-actions">
              <button class="btn btn-primary" @click="getNewQuote">换一句</button>
              <!-- #ifndef MP-WEIXIN -->
              <button class="btn btn-success" @click="shareQuote">分享</button>
              <!-- #endif -->
              <!-- #ifdef MP-WEIXIN -->
              <button class="btn btn-success" open-type="share">分享</button>
              <!-- #endif -->
            </view>
          </view>

        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { Bubble, FingerSequenceItem } from '../../types/global.d.ts'

// 响应式数据
const showGame = ref<boolean>(false)
const currentGame = ref<string>('')
const gameTitle = ref<string>('')

// 泡泡游戏
const bubbles = reactive<Bubble[]>([])
const bubbleScore = ref<number>(0)
const bubbleGameActive = ref<boolean>(false)

// 花朵呼吸
const flowerBlooming = ref<boolean>(false)
const flowerText = ref<string>('点击开始呼吸')
const flowerActive = ref<boolean>(false)

// 专注训练
const targetX = ref(250)
const targetY = ref(250)
const focusHits = ref(0)
const focusTime = ref(0)
const focusActive = ref(false)

// 手指训练
const fingerSequence = reactive<FingerSequenceItem[]>([])
const currentFingerIndex = ref(0)
const fingerProgress = ref(0)

// 数字游戏
const numberQuestion = ref('')
const numberAnswer = ref('')
const numberCorrect = ref(0)
const numberWrong = ref(0)
const correctAnswer = ref(0)

// 励志语录
const currentQuote = ref({ text: '', author: '' })

// 励志语录数据
const quotes = [
  { text: '每一次拒绝香烟，都是对健康的投资', author: '戒烟小助手' },
  { text: '你的意志力比任何成瘾都要强大', author: '戒烟小助手' },
  { text: '成功不是终点，失败不是末日，继续前进的勇气才最重要', author: '丘吉尔' },
  { text: '改变是痛苦的，但不改变会更痛苦', author: '戒烟小助手' },
  { text: '每天进步一点点，一年后你会感谢今天的自己', author: '戒烟小助手' },
  { text: '戒烟不是剥夺，而是解放', author: '戒烟小助手' },
  { text: '你已经比昨天的自己更强大了', author: '戒烟小助手' },
  { text: '健康是最大的财富', author: '戒烟小助手' }
]

// 方法
const openGame = (gameType: string) => {
  currentGame.value = gameType
  showGame.value = true
  
  switch (gameType) {
    case 'bubble':
      gameTitle.value = '泡泡消消乐'
      break
    case 'flower':
      gameTitle.value = '花朵呼吸'
      break
    case 'focus':
      gameTitle.value = '专注训练'
      initFocusGame()
      break
    case 'finger':
      gameTitle.value = '手指训练'
      initFingerGame()
      break
    case 'number':
      gameTitle.value = '数字挑战'
      generateNumberQuestion()
      break
    case 'quote':
      gameTitle.value = '励志语录'
      getNewQuote()
      break
  }
}

const closeGame = () => {
  showGame.value = false
  // 清理定时器
  if (bubbleGameActive.value) {
    bubbleGameActive.value = false
  }
  if (flowerActive.value) {
    flowerActive.value = false
  }
  if (focusActive.value) {
    focusActive.value = false
  }

  if (focusTimeInterval) {
    clearInterval(focusTimeInterval)
    focusTimeInterval = null
  }
}

// 泡泡游戏方法
const createBubble = () => {
  const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#feca57', '#ff9ff3', '#54a0ff']
  return {
    id: Date.now() + Math.random(),
    x: Math.random() * 400,
    y: Math.random() * 400,
    color: colors[Math.floor(Math.random() * colors.length)]
  }
}

const startBubbleGame = () => {
  bubbleGameActive.value = true
  bubbleScore.value = 0
  bubbles.splice(0, bubbles.length)
  
  const gameLoop = () => {
    if (bubbleGameActive.value) {
      if (Math.random() < 0.7) {
        bubbles.push(createBubble())
      }
      setTimeout(gameLoop, 1000)
    }
  }
  gameLoop()
}

const popBubble = (index: number) => {
  bubbles.splice(index, 1)
  bubbleScore.value += 10
  
  // 触觉反馈
  uni.vibrateShort()
}

// 花朵呼吸方法
const startFlowerBreathing = () => {
  if (flowerActive.value) {
    flowerActive.value = false
    flowerText.value = '点击开始呼吸'
    return
  }
  
  flowerActive.value = true
  breathingCycle()
}

const breathingCycle = () => {
  if (!flowerActive.value) return
  
  // 吸气
  flowerText.value = '慢慢吸气...'
  flowerBlooming.value = true
  
  setTimeout(() => {
    if (!flowerActive.value) return
    // 呼气
    flowerText.value = '慢慢呼气...'
    flowerBlooming.value = false
    
    setTimeout(() => {
      if (flowerActive.value) {
        breathingCycle()
      }
    }, 4000)
  }, 4000)
}

// 专注训练方法
const initFocusGame = () => {
  targetX.value = 250
  targetY.value = 250
  focusHits.value = 0
  focusTime.value = 0
}

let focusTimeInterval: ReturnType<typeof setInterval> | null = null

const startFocusGame = () => {
  focusActive.value = true
  focusHits.value = 0
  focusTime.value = 30
  
  moveTarget()
  
  focusTimeInterval = setInterval(() => {
    focusTime.value--
    if (focusTime.value <= 0) {
      clearInterval(focusTimeInterval!)
      focusActive.value = false
      uni.showToast({
        title: `游戏结束！命中${focusHits.value}次`,
        icon: 'none'
      })
    }
  }, 1000)
}

const moveTarget = () => {
  if (focusActive.value) {
    targetX.value = Math.random() * 400
    targetY.value = Math.random() * 300
    setTimeout(moveTarget, 2000)
  }
}

const hitTarget = () => {
  if (focusActive.value) {
    focusHits.value++
    targetX.value = Math.random() * 400
    targetY.value = Math.random() * 300
  }
}

// 手指训练方法
const initFingerGame = () => {
  const fingers = ['👍', '👆', '🤞', '🤟', '🤘']
  fingerSequence.splice(0, fingerSequence.length)
  
  for (let i = 0; i < 5; i++) {
    fingerSequence.push({
      emoji: fingers[Math.floor(Math.random() * fingers.length)],
      pressed: false
    })
  }
  
  currentFingerIndex.value = 0
  fingerProgress.value = 0
}

const startFingerGame = () => {
  initFingerGame()
}

const pressFinger = (index: number) => {
  if (index === currentFingerIndex.value) {
    fingerSequence[index].pressed = true
    fingerProgress.value++
    currentFingerIndex.value++
    
    if (fingerProgress.value === fingerSequence.length) {
      uni.showToast({
        title: '完成！',
        icon: 'success'
      })
      setTimeout(initFingerGame, 1000)
    }
  }
}

// 数字游戏方法
const generateNumberQuestion = () => {
  const a = Math.floor(Math.random() * 50) + 1
  const b = Math.floor(Math.random() * 50) + 1
  const operations = a > b ? ['+', '-', '×'] : ['+', '×']
  const op = operations[Math.floor(Math.random() * operations.length)]
  
  numberQuestion.value = `${a} ${op} ${b} = ?`
  
  switch (op) {
    case '+':
      correctAnswer.value = a + b
      break
    case '-':
      correctAnswer.value = a - b
      break
    case '×':
      correctAnswer.value = a * b
      break
    }

  numberAnswer.value = ''
}

const checkAnswer = () => {
  if (parseInt(numberAnswer.value) === correctAnswer.value) {
    numberCorrect.value++
    uni.showToast({
      title: '答对了！',
      icon: 'success'
    })
  } else {
    numberWrong.value++
    uni.showToast({
      title: `答错了，正确答案是${correctAnswer.value}`,
      icon: 'none'
    })
  }
  
  setTimeout(generateNumberQuestion, 1000)
}

// 励志语录方法
const getNewQuote = () => {
  const randomIndex = Math.floor(Math.random() * quotes.length)
  currentQuote.value = quotes[randomIndex]
}

const shareQuote = () => {
  //#ifndef MP-WEIXIN
  uni.showActionSheet({
    itemList: ['复制文字'],
    success: (res) => {
      if (res.tapIndex === 0) {
        uni.setClipboardData({
          data: currentQuote.value.text + ' —— ' + currentQuote.value.author
        })
      }
    }
  })
  //#endif
}
</script>

<script lang="ts">
// 微信小程序分享功能配置
export default {
  onShareAppMessage() {
    return {
      title: '戒烟伙伴 - 你的戒烟伴侣',
      path: '/pages/games/games',
      imageUrl: '/static/logo144.png' // 可选：自定义分享图片
    }
  }
}
</script>

<style lang="scss" scoped>
.games-container {
  padding: 20rpx;
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.game-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 20rpx;
  text-align: center;
  transition: transform 0.3s ease;
  
  &:active {
    transform: scale(0.95);
  }
  
  .game-icon {
    font-size: 64rpx;
    margin-bottom: 20rpx;
  }
  
  .game-content {
    flex: 1;
    
    .game-name {
      display: block;
      font-size: 28rpx;
      font-weight: 600;
      margin-bottom: 8rpx;
    }
    
    .game-desc {
      font-size: 22rpx;
      color: #666;
    }
  }
  
  .game-arrow {
    font-size: 20rpx;
    color: #667eea;
    margin-top: 15rpx;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.modal-content {
  width: 600rpx;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .modal-title {
    font-size: 32rpx;
    font-weight: 600;
  }
  
  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    background: #f5f5f5;
    font-size: 24rpx;
  }
}

.modal-body {
  padding: 30rpx;
  height: 60vh;
  overflow: hidden;
}

// 泡泡游戏样式
.bubble-game {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.game-area {
  flex: 1;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  overflow: hidden;
}

.bubble {
  position: absolute;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20rpx); }
}

.game-stats {
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .score {
    font-size: 28rpx;
    font-weight: 600;
    color: #667eea;
  }
}

// 花朵呼吸样式
.flower-game {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.flower-container {
  text-align: center;
  margin-bottom: 60rpx;
}

.flower {
  font-size: 120rpx;
  transition: transform 4s ease-in-out;
  display: block;
  margin-bottom: 30rpx;
  
  &.blooming {
    transform: scale(1.3);
  }
}

.flower-text {
  font-size: 28rpx;
  color: #667eea;
}

// 专注训练样式
.focus-game {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.focus-area {
  flex: 1;
  position: relative;
  background: #f8f9fa;
  border-radius: 16rpx;
  
  .focus-target {
    position: absolute;
    font-size: 48rpx;
    transition: all 0.5s ease;
  }
}

.focus-stats {
  padding: 20rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .hits, .time {
    font-size: 24rpx;
    color: #667eea;
  }
}

// 手指训练样式
.finger-game {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.finger-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.finger-sequence {
  display: flex;
  gap: 20rpx;
  
  .finger-btn {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 48rpx;
    border-radius: 16rpx;
    background: #f8f9fa;
    transition: all 0.3s ease;
    
    &.active {
      background: #667eea;
      transform: scale(1.1);
    }
    
    &.pressed {
      background: #4caf50;
    }
  }
}

.finger-stats {
  padding: 20rpx 0;
  text-align: center;
  
  .progress {
    display: block;
    font-size: 24rpx;
    color: #667eea;
    margin-bottom: 20rpx;
  }
}

// 数字游戏样式
.number-game {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.number-question {
  margin-bottom: 40rpx;
  
  .question {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
  }
}

.number-input {
  display: flex;
  gap: 20rpx;
  margin-bottom: 40rpx;
  
  input {
    width: 200rpx;
    height: 80rpx;
    padding: 0 20rpx;
    border: 2rpx solid #e9ecef;
    border-radius: 12rpx;
    font-size: 28rpx;
    text-align: center;
  }
}

.number-stats {
  display: flex;
  gap: 40rpx;
  
  .correct, .wrong {
    font-size: 24rpx;
    color: #667eea;
  }
}

// 励志语录样式
.quote-game {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.quote-container {
  text-align: center;
  margin-bottom: 60rpx;
  
  .quote-text {
    display: block;
    font-size: 32rpx;
    line-height: 1.6;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .quote-author {
    font-size: 24rpx;
    color: #667eea;
    font-style: italic;
  }
}

.quote-actions {
  display: flex;
  gap: 20rpx;
}
</style>